#include "fileops.h"
#include <stdio.h>
#include <stdlib.h>

StudentList* loadStudentsFromFile(const char *filename) {
    FILE *file = fopen(filename, "r");
    StudentList* list = (StudentList*)malloc(sizeof(StudentList));
    list->head = NULL;
    list->count = 0;

    if (file == NULL) {
        printf("无法打开文件：%s\n", filename);
        return list;
    }

    Student student;
    while (fscanf(file, "%d,%49[^,],%d,%9[^,],%99[^,],%49[^,],%f\n",
                  &student.id, student.name, &student.age, student.gender,
                  student.major, student.class_name, &student.score) != EOF) {
        StudentNode *newNode = (StudentNode*)malloc(sizeof(StudentNode));
        newNode->data = student;
        newNode->next = list->head;
        list->head = newNode;
        list->count++;
    }
    fclose(file);
    printf("学生信息已从 %s 文件中加载。\n", filename);
    return list;
}

void saveStudentsToFile(const StudentList *list, const char *filename) {
    FILE *file = fopen(filename, "w");
    if (file == NULL) {
        printf("无法打开文件：%s\n", filename);
        return;
    }

    StudentNode *current = list->head;
    while (current != NULL) {
        fprintf(file, "%d,%s,%d,%s,%s,%s,%.2f\n",
                current->data.id, current->data.name, current->data.age,
                current->data.gender, current->data.major,
                current->data.class_name, current->data.score);
        current = current->next;
    }
    fclose(file);
    printf("学生信息已保存到 %s 文件。\n", filename);
}
